package com.xaicode.learn.java.thread;

import java.util.concurrent.Semaphore;
import java.util.concurrent.SynchronousQueue;

/**
 * synchronous queue
 *
 * @author Locker cjxia@isoftstone.com
 * @version 1.0
 */
public class QueueSynchronous {

    public static void main(String[] args) {
        System.out.println("begin:" + (System.currentTimeMillis() / 1000));
        final SynchronousQueue<String> sq = new SynchronousQueue<>();
        final Semaphore sem = new Semaphore(1);
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                try {
                    sem.acquire();
                    String input = sq.take();
                    String output = TestDo.doSome(input);
                    System.out.println(Thread.currentThread().getName() + " : " + output);
                    sem.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        }
        for (int i = 0; i < 10; i++) {
            String input = i + "";
            try {
                sq.put(input);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static class TestDo {
        public static String doSome(String input) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return input + ":" + (System.currentTimeMillis() / 1000);
        }
    }

}
